package com.cx.zyx.modulebiz.news.controller;


import com.cx.zyx.modulebiz.news.controller.vo.TopNewsRespVO;
import com.cx.zyx.modulebiz.news.model.News;
import com.cx.zyx.modulebiz.news.remote.service.comment.CommentFeign;
import com.cx.zyx.modulebiz.news.service.NewsService;
import com.cx.zyx.modulebiz.news.service.dto.TopNewsDTO;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 新闻管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @Autowired
    private CommentFeign commentFeign;

    /**
     * 获取所有新闻列表
     *
     * @return 新闻列表
     */
    @GetMapping
    public ResponseEntity<List<News>> getAllNews(HttpSession session) {
        List<News> newsList = newsService.list();
        log.info("用户|{}|获取所有新闻列表", session.getAttribute("account"));
        return ResponseEntity.ok(newsList);
    }

    /**
     * 获取最新N条新闻列表
     *
     * @param n 新闻数量
     * @return 新闻列表
     */
    @GetMapping("/top/{n}")
    public ResponseEntity<List<TopNewsRespVO>> getTopNews(@PathVariable Optional<Integer> n) {
        Integer size = n.orElse(5); // 默认值为 5
        // 获取Redis中统计最新N条新闻
        List<TopNewsDTO> topNews = newsService.getTopNews(size);

        List<TopNewsRespVO> newsList = topNews.stream().map(news -> {
            TopNewsRespVO newsVO = new TopNewsRespVO();
            newsVO.setId(Math.toIntExact(news.getId()));
            newsVO.setViews(news.getViews());
            newsVO.setOrder(news.getOrder());
            News oneNewsWith = newsService.getOneNewsWith(news.getId());
            newsVO.setTitle(oneNewsWith.getTitle());
            newsVO.setContent(oneNewsWith.getContent());
            newsVO.setCategoryId(oneNewsWith.getCategoryId());
            return newsVO;
        }).toList();
        return ResponseEntity.ok(newsList);
    }

    /**
     * 根据ID获取新闻信息
     *
     * @param id 新闻ID
     * @return 新闻对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<News> getNewsById(@PathVariable Integer id) {
//        News news = newsService.getOneNewsWith(Long.valueOf(id));
        News news = newsService.getNewsByIdNewsWith(Long.valueOf(id));
        return ResponseEntity.ok(news);
    }

    /**
     * 创建新新闻
     *
     * @param news 新闻对象
     * @return 带状态码的响应结果
     */
    //@GlobalTransactional(name = "create-news", rollbackFor = Exception.class)
    @Transactional
    @PostMapping
    public ResponseEntity<News> createNews(@RequestBody News news) {
        boolean saved = newsService.save(news);

        if (saved) {
            // 消息队列解耦微服务之间的通信方式
            newsService.sendNormalMessage("news-topic", "NEW | " + news.getCategoryId(), news);
            // 添加新闻对应的评论
//            Comment comment = new Comment();
//            comment.setContent("新闻的评论:" + news.getTitle());
//            comment.setNewsId(news.getId());
//            comment.setUserId(1);
//            boolean result = commentFeign.createComment(comment);
//            if (!result){
//                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
//            }
            return ResponseEntity.status(HttpStatus.CREATED).body(news);
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 创建延迟新闻
     *
     * @param news 新闻对象
     * @return 带状态码的响应结果
     */
    @PostMapping("/delay")
    public ResponseEntity<News> createDelayedNews(@RequestBody News news) {
        long delay = 3;
        newsService.sendDelayMessage("delay-news-topic", "DELAY", news, delay);
        return ResponseEntity.status(HttpStatus.CREATED).body(news);
    }

    /**
     * 更新指定ID的新闻信息
     *
     * @param id 新闻ID
     * @param news 新闻对象
     * @return 带状态码的响应结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<News> updateNews(@PathVariable Integer id, @RequestBody News news) {
        news.setId(id);
        boolean updated = newsService.updateById(news);
        if (updated) {
            return ResponseEntity.ok(news);
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 删除指定ID的新闻
     *
     * @param id 新闻ID
     * @return 成功返回200，失败返回500
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteNews(@PathVariable Integer id) {
        News deletedItem = newsService.getById(id);
        boolean deleted = newsService.removeById(id);
        if (deleted) {
            // 消息队列解耦微服务之间的通信方式
            newsService.sendNormalMessage("news-topic", "DEL" + deletedItem.getCategoryId(), deletedItem);
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
